from pms.common.views import PostFormula
from user.models import User
from django.db.models.deletion import ProtectedError
from project.models import Project


class API(PostFormula):

    require_permissions = [8]

    def handle(self, req):
        try:
            uid = req['id']
            user = User.objects.get(id=uid)
            delete_uid = user.id
            user.delete()
            return self.success_respond({
                'id': delete_uid
            })
        except ProtectedError as e:
            protected_object = e.protected_objects.pop()
            if isinstance(protected_object, Project):
                return self.failed_respond('PROJECT_LEADER_PROTECT', '该用户是[{}]{}项目的负责人，故不能删除'
                                           .format(protected_object.id, protected_object.name))
